import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { login as loginApi } from "@/apis/auth.js";
import { addUser } from "@/apis/user.js";
import { addEnterprise } from "@/apis/enterprise.js";
import { useUserStore } from "@/store/modules/user.js";

export function useAuth() {
  const router = useRouter();
  const route = useRoute();
  const loading = ref(false);
  const userStore = useUserStore();
  
  // 表单类型：login, register, enterprise
  const formType = ref('login');
  
  // 切换表单类型
  const switchForm = (type) => {
    formType.value = type;
    resetForms();
  };
  
  // 登录表单数据
  const loginForm = reactive({
    username: "",
    password: "",
    rememberMe: false,
  });
  
  // 注册表单数据
  const registerForm = reactive({
    username: "",
    password: "",
    confirmPassword: "",
    phone: "",
    email: ""
  });
  
  // 企业入驻表单数据
  const enterpriseForm = reactive({
    name: "",
    description: "",
    contactName: "",
    contactPhone: "",
    contactEmail: "",
    address: ""
  });
  
  // 登录表单验证规则
  const loginRules = {
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 1, max: 20, message: "用户名长度在 1 到 20 个字符", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 1, max: 20, message: "密码长度在 1 到 20 个字符", trigger: "blur" },
    ],
  };
  
  // 注册表单验证规则
  const registerRules = {
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 1, max: 20, message: "用户名长度在 1 到 20 个字符", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
    ],
    confirmPassword: [
      { required: true, message: "请确认密码", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value !== registerForm.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    phone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
    ],
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { type: 'email', message: "请输入正确的邮箱地址", trigger: "blur" }
    ]
  };
  
  // 企业入驻表单验证规则
  const enterpriseRules = {
    name: [
      { required: true, message: "请输入企业名称", trigger: "blur" },
      { min: 1, max: 100, message: "企业名称长度在 1 到 100 个字符", trigger: "blur" },
    ],
    contactName: [
      { required: true, message: "请输入联系人姓名", trigger: "blur" },
      { min: 1, max: 50, message: "联系人姓名长度在 1 到 50 个字符", trigger: "blur" },
    ],
    contactPhone: [
      { required: true, message: "请输入联系人电话", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
    ],
    contactEmail: [
      { required: true, message: "请输入联系人邮箱", trigger: "blur" },
      { type: 'email', message: "请输入正确的邮箱地址", trigger: "blur" }
    ],
    address: [
      { required: true, message: "请输入企业地址", trigger: "blur" },
      { min: 1, max: 200, message: "企业地址长度在 1 到 200 个字符", trigger: "blur" },
    ]
  };
  
  // 重置所有表单
  const resetForms = () => {
    // 保留登录表单的记住密码功能
    const rememberMe = loginForm.rememberMe;
    Object.assign(loginForm, {
      username: "",
      password: "",
      rememberMe
    });
    
    Object.assign(registerForm, {
      username: "",
      password: "",
      confirmPassword: "",
      phone: "",
      email: ""
    });
    
    Object.assign(enterpriseForm, {
      name: "",
      description: "",
      contactName: "",
      contactPhone: "",
      contactEmail: "",
      address: ""
    });
  };
  
  // 处理登录
  const handleLogin = async () => {
    loading.value = true;
    try {
      // 调用后端登录接口
      const response = await loginApi(loginForm);

      // 假设后端返回格式：{ code: 200, message: 'success', data: { token: 'xxx', username: 'xxx', userType: 'xxx' } }
      const { code, message, data } = response;

      if (code === 200 && data) {
        // 存储token
        localStorage.setItem("token", data.token);

        // 使用userStore设置用户信息，包含userType和enterpriseId
        userStore.setUserInfo({
          id: data.id || data.userId, // 从后端返回的数据中获取用户ID
          username: data.username,
          userType: data.userType,
          enterpriseId: data.enterpriseId || null // 从后端返回的数据中获取企业ID
        });

        // 如果勾选了记住密码，存储用户名
        if (loginForm.rememberMe) {
          localStorage.setItem("username", loginForm.username);
        } else {
          localStorage.removeItem("username");
        }

        ElMessage.success("登录成功");

        // 处理重定向
        const redirect = route.query.redirect || "/";
        router.push(redirect);
      } else {
        throw new Error(message || "登录失败，请重试");
      }
    } catch (error) {
      // 处理错误情况
      if (error.response && error.response.data) {
        // 服务器返回的错误
        ElMessage.error(error.response.data.message || "登录失败，请重试");
      } else {
        // 其他错误
        ElMessage.error(error.message || "网络错误，请稍后重试");
      }
    } finally {
      loading.value = false;
    }
  };
  
  // 处理注册
  const handleRegister = async () => {
    loading.value = true;
    try {
      // 准备注册数据
      const userData = {
        username: registerForm.username,
        password: registerForm.password,
        phone: registerForm.phone,
        email: registerForm.email,
        userType: 1, // 普通用户
        status: 1 // 默认启用
      };
      
      // 调用注册接口
      const response = await addUser(userData);
      
      const { code, message } = response;
      
      if (code === 200) {
        ElMessage.success("注册成功，请登录");
        // 切换到登录表单
        switchForm('login');
      } else {
        throw new Error(message || "注册失败，请重试");
      }
    } catch (error) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.message || "注册失败，请重试");
      } else {
        ElMessage.error(error.message || "网络错误，请稍后重试");
      }
    } finally {
      loading.value = false;
    }
  };
  
  // 处理企业入驻
  const handleEnterpriseRegister = async () => {
    loading.value = true;
    try {
      // 调用企业入驻接口
      const response = await addEnterprise(enterpriseForm);
      
      const { code, message } = response;
      
      if (code === 200) {
        ElMessage.success("企业信息提交成功，请等待审核");
        // 切换到登录表单
        switchForm('login');
      } else {
        throw new Error(message || "企业信息提交失败，请重试");
      }
    } catch (error) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.message || "企业信息提交失败，请重试");
      } else {
        ElMessage.error(error.message || "网络错误，请稍后重试");
      }
    } finally {
      loading.value = false;
    }
  };
  
  // 初始化登录表单
  const initForm = () => {
    const savedUsername = localStorage.getItem("username");
    if (savedUsername) {
      loginForm.username = savedUsername;
      loginForm.rememberMe = true;
    }
  };
  
  return {
    // 状态
    formType,
    loading,
    
    // 表单数据
    loginForm,
    registerForm,
    enterpriseForm,
    
    // 验证规则
    loginRules,
    registerRules,
    enterpriseRules,
    
    // 方法
    switchForm,
    handleLogin,
    handleRegister,
    handleEnterpriseRegister,
    initForm
  };
}